package com.zhijian.wharf.job;

import com.zhijian.wharf.entity.po.DatabaseBackups;
import com.zhijian.wharf.service.DatabaseBackupsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author HCG
 * @version 1.0
 * @date 2024-08-16
 */
@Service
public class MysqlDumpJob {

    /**
     * mysql用户名
     */
    @Value("${spring.datasource.username}")
    private String username;

    /**
     * mysql密码
     */
    @Value("${spring.datasource.password}")
    private String password;

    @Value("${dump.mysql.host}")
    private String host;

    @Value("${path.dumpPath}")
    private String path;

    @Autowired
    private DatabaseBackupsService databaseBackupsService;

    /**
     * 一天执行一次
     */
    @Scheduled(cron = "${job.point.cron:0 1 1 * * * }")
    public void handle() {

        //要备份的数据库名
        String databaseName = "iot-wharf";
        String fileName = System.currentTimeMillis() + ".sql";

        // 备份文件路径
        String backupFilePath = String.format("%s%s", path, fileName);

        String command = "mysqldump -u " + username + " -p" + password + " -h " + host + " " + databaseName + " -r " + backupFilePath;

        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(command);

            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String line;
            while ((line = errorReader.readLine()) != null) {
                System.out.println(line);
            }

            int exitVal = process.waitFor();
            if (exitVal == 0) {
                DatabaseBackups databaseBackups = new DatabaseBackups();
                databaseBackups.setFileName(fileName);
                databaseBackups.setFilePath(backupFilePath);
                databaseBackupsService.insert(databaseBackups);
                System.out.println("Backup completed successfully.");
            } else {
                System.out.println("Backup failed.");
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
